import 'dart:convert';
import 'dart:typed_data';

abstract class WechatQrauthResp {
  const WechatQrauthResp();

  Map<String, dynamic> toJson();

  @override
  String toString() => const JsonEncoder.withIndent('  ').convert(toJson());
}

class WechatGotQrcodeResp extends WechatQrauthResp {
  const WechatGotQrcodeResp({
    required this.imageData,
  });

  factory WechatGotQrcodeResp.fromJson(Map<String, dynamic> json) {
    return WechatGotQrcodeResp(
      imageData: _byteArrayFromJson(json['imageData']),
    );
  }

  final Uint8List imageData;

  @override
  Map<String, dynamic> toJson() {
    return {
      'imageData': imageData,
    };
  }

  static Uint8List _byteArrayFromJson(Object? json) {
    return Uint8List.fromList((json as List<dynamic>).map((e) => e as int).toList());
  }
}

class WechatQrcodeScannedResp extends WechatQrauthResp {
  const WechatQrcodeScannedResp();

  factory WechatQrcodeScannedResp.fromJson(Map<String, dynamic> json) {
    return const WechatQrcodeScannedResp();
  }

  @override
  Map<String, dynamic> toJson() {
    return {};
  }
}

class WechatFinishResp extends WechatQrauthResp {
  const WechatFinishResp({
    required this.errorCode,
    this.authCode,
  });

  factory WechatFinishResp.fromJson(Map<String, dynamic> json) {
    return WechatFinishResp(
      errorCode: json['errorCode'] ?? kErrorCodeSuccess,
      authCode: json['authCode'],
    );
  }

  /// Auth成功
  static const int kErrorCodeSuccess = 0;

  /// 普通错误
  static const int kErrorCodeNormal = -1;

  /// 网络错误
  static const int kErrorCodeNetwork = -2;

  /// 获取二维码失败
  static const int kErrorCodeGetQrcodeFailed = -3;

  /// 用户取消授权
  static const int kErrorCodeCancel = -4;

  /// 超时
  static const int kErrorCodeTimeout = -5;

  final int errorCode;
  final String? authCode;

  bool get isSuccessful => errorCode == kErrorCodeSuccess;

  bool get isCancelled => errorCode == kErrorCodeCancel;

  @override
  Map<String, dynamic> toJson() {
    return {
      'errorCode': errorCode,
      'authCode': authCode,
    };
  }
}
